/**
 * 中医闻诊智能综合系统 - 交互脚本
 * 云秒科技
 */

// ========== 全局变量 ==========
const navbar = document.getElementById('navbar');
const hamburger = document.getElementById('hamburger');
const navMenu = document.getElementById('navMenu');
const navLinks = document.querySelectorAll('.nav-link');
const accordionItems = document.querySelectorAll('.accordion-item');

// ========== 导航栏滚动效果 ==========
window.addEventListener('scroll', () => {
    if (window.scrollY > 100) {
        navbar.classList.add('scrolled');
    } else {
        navbar.classList.remove('scrolled');
    }
});

// ========== 移动端汉堡菜单 ==========
hamburger.addEventListener('click', () => {
    navMenu.classList.toggle('active');
    hamburger.classList.toggle('active');
});

// ========== 平滑滚动到锚点 ==========
navLinks.forEach(link => {
    link.addEventListener('click', (e) => {
        const href = link.getAttribute('href') || '';

        // 仅当是站内锚点(#section)时拦截，做平滑滚动；
        // 多页面链接(.html)保持默认跳转
        if (href.startsWith('#')) {
            e.preventDefault();

            // 移除所有active类
            navLinks.forEach(l => l.classList.remove('active'));
            // 添加active到当前链接
            link.classList.add('active');

            // 获取目标section
            const targetSection = document.querySelector(href);

            if (targetSection) {
                const offsetTop = targetSection.offsetTop - 70; // 减去导航栏高度
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
            }

            // 关闭移动端菜单
            navMenu.classList.remove('active');
            hamburger.classList.remove('active');
        }
    });
});

// ========== 手风琴效果 ==========
accordionItems.forEach(item => {
    const header = item.querySelector('.accordion-header');
    
    header.addEventListener('click', () => {
        const isActive = item.classList.contains('active');
        
        // 关闭所有accordion
        accordionItems.forEach(i => i.classList.remove('active'));
        
        // 如果当前不是active状态，则打开
        if (!isActive) {
            item.classList.add('active');
        }
    });
});

// 默认打开第一个accordion
if (accordionItems.length > 0) {
    accordionItems[0].classList.add('active');
}

// ========== 滚动动画 ==========
// 观察器配置
const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -100px 0px'
};

// 创建观察器
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.style.opacity = '1';
            entry.target.style.transform = 'translateY(0)';
        }
    });
}, observerOptions);

// 观察所有需要动画的元素
const animatedElements = document.querySelectorAll('.advantage-card, .scenario-card, .device-card');
animatedElements.forEach(el => {
    el.style.opacity = '0';
    el.style.transform = 'translateY(30px)';
    el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    observer.observe(el);
});

// ========== 当前激活导航项 ==========
// 根据滚动位置更新导航active状态
window.addEventListener('scroll', () => {
    let current = '';
    const sections = document.querySelectorAll('section[id]');
    
    sections.forEach(section => {
        const sectionTop = section.offsetTop;
        const sectionHeight = section.clientHeight;
        
        if (window.scrollY >= sectionTop - 150) {
            current = section.getAttribute('id');
        }
    });
    
    navLinks.forEach(link => {
        link.classList.remove('active');
        if (link.getAttribute('href') === `#${current}`) {
            link.classList.add('active');
        }
    });
});

// ========== 图片懒加载 ==========
if ('loading' in HTMLImageElement.prototype) {
    // 浏览器支持原生懒加载：若存在 data-src 则迁移到 src；否则保持原 src 不动
    const images = document.querySelectorAll('img[loading="lazy"]');
    images.forEach(img => {
        const dataSrc = img.dataset && img.dataset.src;
        if (dataSrc) {
            img.src = dataSrc;
        }
    });
} else {
    // 降级方案：使用Intersection Observer
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                const dataSrc = img.dataset && img.dataset.src;
                if (dataSrc) {
                    img.src = dataSrc;
                }
                img.classList.remove('lazy');
                imageObserver.unobserve(img);
            }
        });
    });
    
    const lazyImages = document.querySelectorAll('img.lazy');
    lazyImages.forEach(img => imageObserver.observe(img));
}

// ========== 返回顶部按钮 ==========
// 创建返回顶部按钮
const backToTopButton = document.createElement('button');
backToTopButton.innerHTML = '<i class="fas fa-arrow-up"></i>';
backToTopButton.className = 'back-to-top';
backToTopButton.setAttribute('aria-label', '返回顶部');
document.body.appendChild(backToTopButton);

// 添加样式
const style = document.createElement('style');
style.textContent = `
    .back-to-top {
        position: fixed;
        bottom: 30px;
        right: 30px;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: var(--primary-color);
        color: white;
        border: none;
        cursor: pointer;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
        box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        z-index: 999;
    }
    
    .back-to-top.show {
        opacity: 1;
        visibility: visible;
    }
    
    .back-to-top:hover {
        background: var(--primary-light);
        transform: translateY(-5px);
    }
`;
document.head.appendChild(style);

// 显示/隐藏按钮
window.addEventListener('scroll', () => {
    if (window.scrollY > 500) {
        backToTopButton.classList.add('show');
    } else {
        backToTopButton.classList.remove('show');
    }
});

// 点击返回顶部
backToTopButton.addEventListener('click', () => {
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
});

// ========== 页面加载完成 ==========
window.addEventListener('load', () => {
    console.log('页面加载完成');
    
    // 添加加载动画完成类
    document.body.classList.add('loaded');
});

// ========== 性能优化：防抖函数 ==========
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// ========== 窗口调整大小时的处理 ==========
const handleResize = debounce(() => {
    // 如果窗口宽度大于768px，确保移动端菜单关闭
    if (window.innerWidth > 768) {
        navMenu.classList.remove('active');
        hamburger.classList.remove('active');
    }
}, 250);

window.addEventListener('resize', handleResize);

// ========== 打印控制台信息 ==========
console.log('%c云秒科技 - 中医闻诊智能综合系统', 'color: #1a365d; font-size: 20px; font-weight: bold;');
console.log('%c让数据更懂中医，让中医更懂每一个人', 'color: #2d74b8; font-size: 14px;');

// ========== Banner 轮播 ==========
(function initBanner(){
    const banner = document.querySelector('.banner');
    if(!banner) return;
    const slides = banner.querySelectorAll('.slide');
    const dotsContainer = document.getElementById('bannerDots');
    let index = 0;
    const show = (i)=>{
        slides.forEach((s,idx)=> s.classList.toggle('active', idx===i));
        if(dotsContainer){
            dotsContainer.querySelectorAll('button').forEach((d,idx)=> d.classList.toggle('active', idx===i));
        }
        index = i;
    };
    // dots
    slides.forEach((_,i)=>{
        const dot = document.createElement('button');
        dot.addEventListener('click', ()=>show(i));
        dotsContainer.appendChild(dot);
    });
    show(0);
    setInterval(()=>{
        const next = (index + 1) % slides.length;
        show(next);
    }, 5000);
})();

// ========== 产品页：点击左侧菜单切换右侧详情 ==========
(function initProductSwitch(){
    const menuLinks = document.querySelectorAll('.product-sidebar .product-menu a');
    const sections = document.querySelectorAll('.product-section');
    if (menuLinks.length === 0 || sections.length === 0) return;

    const show = (id) => {
        sections.forEach(sec => sec.classList.toggle('active', sec.id === id));
        menuLinks.forEach(a => a.classList.toggle('active', a.getAttribute('href') === `#${id}`));
    };

    // 根据 hash 初始化
    const initId = (location.hash || menuLinks[0].getAttribute('href')).replace('#','');
    show(initId);

    // 点击切换
    menuLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const id = link.getAttribute('href').replace('#','');
            history.replaceState(null, '', `#${id}`);
            show(id);
        });
    });
})();

